package java6681.lesson13;

/**
 * @author Junichiro
 * @description 多线程的并发冲突
 * @date 2021-06-05 19:17
 **/

public class DrinkWater6681 {
    private static int waters = 20;

    public static void main(String[] args) {
        Thread t1 = new Thread(DrinkWater6681::drinking, "狗");
        Thread t2 = new Thread(DrinkWater6681::drinking, "猫");
        t1.start();
        t2.start();
    }

    private static void drinking() {
        String name = Thread.currentThread().getName();
        while (waters > 0) {
            synchronized (DrinkWater6681.class) {
                if (name.equals("狗")) {
                    waters -= 5;
                } else if (name.equals("猫")) {
                    waters -= 2;
                }
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                if (waters <= 0) {
                    return;
                }
                System.out.println(name + "已喝水，剩" + waters);
            }
        }
        System.out.println(name + "请加水！！！");
    }
}
